//
//  WXHomeTableViewController.swift
//  weibo
//
//  Created by 王旭 on 16/4/16.
//  Copyright © 2016年 王旭. All rights reserved.
//

import UIKit

class WXHomeTableViewController: WXVistorTableViewController {
    
    //定义重用标识符
    private let reuseID = "home_cell"
    
    //定义控制器对应的viewModel
    private lazy var statusListViewModel : WXStatusListViewModel = WXStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        if !isLogin {
            vistorView.setVistorView(nil , image: nil )
            return
        }
        
        setupUI()
        
        loadData()

//        tableView.rowHeight = 200
        
        
    }
    
    func setupUI() {
        //注册cell
        tableView.registerClass(WXHomeCell.self, forCellReuseIdentifier: reuseID)
        
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 250
        //隐藏tabView分割线
        tableView.separatorStyle = .None
        //背景色
        tableView.backgroundColor = UIColor(white: 180/255, alpha: 1)
        //设置上拉视图为footerView
        tableView.tableFooterView = pullView
        
        //添加下拉刷新控件
        tableView.addSubview(refreshView)
        
        refreshView.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)

//-----------------以下为系统自带的下拉刷新方式----------------------------
//        //实例化下拉刷新控件
//        self.refreshControl = UIRefreshControl()
//        //给控件添加事件
//        self.refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
//-----------------以上为系统自带的下拉刷新方式----------------------------
        
        //添加下拉提示控件
        self.navigationController!.view.addSubview(pullNoticeLabel)
        //添加到导航栏的下面
        self.navigationController!.view.insertSubview(pullNoticeLabel, belowSubview: navigationController!.navigationBar)
    }
    
   @objc private func loadData() {
        //加载数据
        statusListViewModel.loadData(pullView.isAnimating()) { (isSuccess,count) -> () in
            if isSuccess {
                self.tableView.reloadData()
            }else{
                print("请求数据失败")
            }
            
            //如果是下拉刷新,显示提示label
            if self.pullView.isAnimating() == false {
                self.showNoticeLabel(count)
            }
            
            self.endRefresh()
        }
    }
    
    //显示下拉提示label
    private func showNoticeLabel(count:Int) {
        //判断是否正在显示
        if pullNoticeLabel.hidden == false {
            return
        }
        //1.确定初始位置
        pullNoticeLabel.frame.origin.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - pullNoticeLabel.frame.height
        pullNoticeLabel.hidden = false
        //2.获取显示的内容
        let text = count>0 ? "\(count)条新微博" :"没有微博数据"
        pullNoticeLabel.text = text
        
        //3.显示动画
        UIView.animateWithDuration(1, animations: { () -> Void in
            //下移
            self.pullNoticeLabel.transform = CGAffineTransformMakeTranslation(0, self.pullNoticeLabel.frame.height)
            
            }) { (_) -> Void in
                
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    //还原
                    self.pullNoticeLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        //隐藏
                        self.pullNoticeLabel.hidden = true
                })
        }
    }
    
    //菊花停转
   private func endRefresh() {
        //上拉视图停转
        pullView.stopAnimating()
        //下拉视图停转
        self.refreshControl?.endRefreshing()
        //上拉视图停止
        refreshView.endRefreshing()
    }
    
    //懒加载下拉的pullView
    private lazy var pullView:UIActivityIndicatorView = {
       let pullView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        //颜色
        pullView.color = UIColor.redColor()
        //--------------------以下为测试代码-----------------
        pullView.hidesWhenStopped = false
        //--------------------以上为测试代码-----------------
        return pullView
    }()
    //懒加载上拉的refreshView
    private lazy var refreshView : WXRefreshControl = WXRefreshControl()
    //懒加载下拉提示label
    private lazy var pullNoticeLabel : UILabel = {
       let pullNoticeLabel = UILabel(textColor: UIColor.whiteColor(), fontSize: 14)
        pullNoticeLabel.frame.size = CGSize(width: SCREEN_W, height: 35)
        pullNoticeLabel.backgroundColor = UIColor.orangeColor()
        pullNoticeLabel.hidden = true
        pullNoticeLabel.textAlignment = .Center
        return pullNoticeLabel
    }()

}



//数据源方法
extension WXHomeTableViewController {
    //将要显示某个cell调用
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        //判断是最后一个cell
        if indexPath.row == statusListViewModel.statusArray!.count - 1 && !pullView.isAnimating() {
            //开始选转
            pullView.startAnimating()
            //加载数据
            loadData()
        }
    }
    //多少行
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return statusListViewModel.statusArray?.count ?? 0

    }
    //每行数据
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //冲用cell,没有自己创建
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID, forIndexPath: indexPath) as! WXHomeCell
       
        //给Label赋值
//        cell.textLabel?.text = statusViewModel.statusArray![indexPath.row].text
        cell.statusViewModel = statusListViewModel.statusArray![indexPath.row]

        
        return cell
        
    }

}